package com.delivery.www.dao.DaoImpl;

import com.delivery.www.dao.SellerDao;
import com.delivery.www.po.Seller;
import com.delivery.www.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SellerDaoImpl implements SellerDao {
    @Override
    public int register(String name, String password, Integer storeId, String email) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {name, password, storeId, email};
        String sql = "insert into seller (seller_name,password,store_id,seller_email)value(?,?,?,?)";
        int i = JdbcUtils.excute(connection, pstm, sql, params);
        JdbcUtils.closeResource(connection, pstm, null);
        return i;
    }

    @Override
    public Seller login(String name, String password) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        String sql = "select * from seller where seller_name =? and password=?";
        Object[] params = {name, password};
        rs = JdbcUtils.excute(connection, pstm, rs, sql, params);
        Seller seller = null;
        try {
            if (rs.next()) {
                seller = new Seller();
                seller.setSellerId(rs.getInt("seller_id"));
                seller.setSellerName(rs.getString("seller_name"));
                seller.setPassword(rs.getString("password"));
                seller.setStoreId(rs.getInt("store_id"));
                seller.setSellerEmail(rs.getString("seller_email"));
                JdbcUtils.closeResource(connection, pstm, rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return seller;
    }

    @Override
    public List<Seller> getSeller() {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<Seller> sellers = new ArrayList<>();
        Object[] params = {};
        String sql = "select s.seller_name from seller s";
        rs = JdbcUtils.excute(connection, pstm, rs, sql, params);
        try {
            while (rs.next()) {
                Seller seller = new Seller();
                seller.setSellerName(rs.getString("seller_name"));
                sellers.add(seller);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JdbcUtils.closeResource(connection, pstm, rs);
        return sellers;
    }
}
